import { findIndex } from 'lodash'

// In case of stacked bar chart Additive sort
// option {Object} eChart option
export const handleSort = (option, sort) => {
  if (option.series.length <= 1) {
    return option
  }
  let countArr = []
  option.xAxis.data.map((item, index) => {
    let count = 0
    option.series.map((items) => {
      if (items.stack && items.stack === 'stack') {
        count = count + (items.data[index] ? Number(items.data[index]) : 0)
      }
    })
    countArr.push({
      key: item,
      value: count,
      index
    })
  })
  countArr.sort((a, b) => {
    if (sort === 'descending') {
      return b.value - a.value
    }
    if (sort === 'ascending') {
      return a.value - b.value
    }
  })
  option.xAxis.data = countArr.map(item => {
    return item.key
  })
  option.series.map(item => {
    const arr = []
    if (item.stack && item.stack === 'stack') {
      item.data.map((items, index) => {
        const itemIndex = findIndex(countArr, { index: index })
        arr[itemIndex] = items
      })
      item.data = arr
    }
    return item
  })
  return option
}

// Show several columns
// option {Object} eChart option
// showNumber {NUmber} gadget setting
export const showColumnLimit = (option, showNumber) => {
  const showColumnLimit = parseInt(showNumber) ? parseInt(showNumber) : null
  if (showColumnLimit) {
    option.xAxis.data = option.xAxis.data.slice(0, showColumnLimit)
  }
  return option
}
